<script setup lang="ts">
import { markRaw, ref, onMounted, unref, toRefs, watch } from "vue";
import Vditor from "vditor";
import "vditor/dist/index.css"

// import {IPackVditor} from "./inter";
const OPS = {

    preview: {
        markdown: {
            autoSpace: true,
            fixTermTypo: true,
        },
        math: {
            inlineDigit: true,
            engine: "MathJax",
            macros: {
                inlineMath: [['$', '$'], ['\\(', '\\)']],
                displayMath: [['$$', '$$'], ["\\[", "\\]"]],
                // equationNumbers: { autoNumber: 'AMS' },
                // options: {
                //     // 隐藏右键菜单
                //     enableMenu: false,
                // },
                // startup: {
                //     typeset: true,
                // },
                // // 配置解析式定位符
                // tex: {

                //     inlineMath: [['$', '$'], ['\\(', '\\)']],
                //     displayMath: [['$$', '$$'], ["\\[", "\\]"]],
                //     equationNumbers: { autoNumber: 'AMS' },
                // },
                // svg: {
                //     fontCache: 'global'
                // },
            }
        }
    },
    mode: "light", cdn: "/vditor-cdn"
}

const props = withDefaults(defineProps<{ modelValue?: any }>(), {
    modelValue: ''
})

const emits = defineEmits<{
    "update:modelValue": [v: string]
}>()

const { modelValue } = toRefs(props);

let value = unref(modelValue);
const vditorRef = ref<HTMLElement>()
const editor = ref<Vditor>()
//
const handleInput = (v: string) => {
    value = v;
    emits("update:modelValue", v)
}
//
watch(modelValue, (v: string) => {
    if (v != value && editor.value) {
        value = v;
        editor.value.setValue(v)
    }
})

onMounted(() => {
    if (!vditorRef.value) return;
    editor.value = markRaw(new Vditor(vditorRef.value,
        {
            value, input: handleInput, cdn: '/vditor-cdn', height: 360, cache: { enable: false },preview:{math:{engine:"MathJax",mathJaxOptions:{
                tex:{
                    inlineMath: [['$', '$'], ['\\(', '\\)']],
                    displayMath: [['$$', '$$'], ["\\[", "\\]"]],
                    // equationNumbers: {autoNumber: 'AMS'},
                },
                startup: {
                        typeset: true,
                    },
                svg: {
                        fontCache: 'global'
                    },
                
            }}}
        })
    )
})


defineExpose({
    editor: unref(editor)
})

</script>


<template>
    <div ref="vditorRef"></div>
</template>
